import React, { useEffect, useState } from 'react';
import Taro, { getCurrentInstance } from '@tarojs/taro';
import { connect } from 'react-redux';
import { View, Button, Image, Text, ScrollView } from '@tarojs/components';
import selectedPng from '@/images/common/selected.png';
import pencilPng from '@/giftCardSubPack/images/giftCard/pencil.png';
import forbiddenPng from '@/orderSubPack/images/confirmOrder/forbidden.png';
import classNames from 'classnames';
import utils from '@/utils/index';

import './index.scss';

const AddressItem = ({ address, edit, changeRadio }) => {
  const { addressStr, contactName, mobile, isTeam, selected, disabled, id, isDefault } = address;

  const forbiddenEle = (
    <View className="forbidden">
      <Image className="icon" src={forbiddenPng}></Image>
    </View>
  );

  const selectedEle = (
    <View
      className="selOp"
      onClick={() => {
        changeRadio(address);
      }}
    >
      {selected ? (
        <View className="selected">
          <Image className="icon" src={selectedPng}></Image>
        </View>
      ) : (
        <View
          className={classNames('unselected', { 'unselected-h5': process.env.TARO_ENV === 'h5' })}
        ></View>
      )}
    </View>
  );

  const statusEle = <>{disabled ? forbiddenEle : selectedEle}</>;

  const editEle = (
    <>
      {isTeam || disabled ? null : (
        <View className="edit" onClick={() => edit(id)}>
          <Image className="icon" src={pencilPng}></Image>
        </View>
      )}
    </>
  );

  return (
    <View className={`address-item ${disabled ? 'disabled' : ''}`}>
      {selected ? <View className="left">{statusEle}</View> : null}

      <View
        className="center"
        onClick={() => {
          changeRadio(address);
        }}
      >
        <View className="user-detail">
          <View className="name">{contactName}</View>
          <View className="phone">{`${mobile}`.replace(/(\d{3})\d*(\d{4})/g, '$1****$2')}</View>
          {!disabled && isDefault === '1' ? <Text className="default-address">默认</Text> : null}
        </View>
        <View className="address-detail">{addressStr}</View>
      </View>
      <View className="right">{editEle}</View>
    </View>
  );
};

const AddressList = ({ list, edit, changeRadio }) => {
  return (
    <View className="take-out-address">
      {list.map((item) => {
        return (
          <View key={item.id || item.addressStr}>
            <AddressItem edit={edit} address={item} changeRadio={changeRadio}></AddressItem>
          </View>
        );
      })}
    </View>
  );
};

const TakeOutAddress = ({
  dispatch,
  allAddresses,
  teamAllAddress,
  teamDefaultAddress,
  defaultAddress,
}) => {
  const { router } = getCurrentInstance();
  const { params = {} } = router;

  const [isRedirecting, setIsRedirecting] = useState(false);

  const isTeam = params.isTeam === '1';

  useEffect(() => {
    if (isTeam && !teamAllAddress?.length) {
      Taro.showModal({
        title: '提示',
        content: '您暂无可用团餐配送地址',
        showCancel: false,
      });
    }
  }, [teamAllAddress]);

  const [addressList, setAddressList] = useState([]);

  const newAdd = () => {
    dispatch({ type: 'giftCard/adressId', payload: null });
    Taro.navigateTo({ url: '/giftCardSubPack/addAddress/index' });
  };

  const edit = (id) => {
    dispatch({ type: 'giftCard/adressId', payload: { id } });
    Taro.navigateTo({ url: `/giftCardSubPack/addAddress/index?id=${id}` });
  };

  const changeRadio = (address) => {
    if (isRedirecting) {
      return;
    }
    setIsRedirecting(true);

    if (address.isTeam) {
      dispatch({
        type: 'otherApi/setTeamDefaultAddress',
        payload: { ...address },
      });
    } else {
      dispatch({
        type: 'productCar/setDefaultAddress',
        payload: { ...address },
      });
    }
    setTimeout(() => {
      Taro.navigateBack();
      setIsRedirecting(false);
    }, 500);
  };

  useEffect(() => {
    const temp = [];
    if (isTeam) {
      temp.push(
        ...(teamAllAddress?.map((item) => {
          return {
            ...item,
            isTeam: true,
            selected:
              item.orgId === teamDefaultAddress.orgId &&
              item.merchantId === teamDefaultAddress.merchantId,
          };
        }) ?? []),
      );
    }

    // 团餐时, 个人收货地址无法使用
    temp.push(
      ...(allAddresses?.map((item) => {
        return {
          ...item,
          disabled: isTeam,
          selected: !isTeam && item.id === defaultAddress.id,
        };
      }) ?? []),
    );

    // 添加 addressStr
    setAddressList(
      temp.map((item) => {
        return {
          ...item,
          addressStr: `${item.address ?? ''}${item.houseNumber ?? ''}`,
        };
      }),
    );
  }, [isTeam, allAddresses, teamAllAddress, defaultAddress, teamDefaultAddress]);

  return (
    <View className="takeoutAddress">
      <ScrollView
        enableFlex
        scrollY
        style={{
          height: `calc(${['100vh', utils.getSizeByScale(182) + 'px'].join(' - ')})`,
        }}
      >
        <AddressList list={addressList} edit={edit} changeRadio={changeRadio}></AddressList>
      </ScrollView>

      {isTeam ? null : (
        <View className="btnBox" onClick={newAdd}>
          <Button className="btn">新增地址</Button>
        </View>
      )}
    </View>
  );
};
export default connect(({ giftCard, otherApi, productCar }) => ({
  allAddresses: giftCard.allAddresses,

  teamAllAddress: otherApi.teamAllAddress,
  teamDefaultAddress: otherApi.teamDefaultAddress,
  defaultAddress: productCar.defaultAddress,
}))(TakeOutAddress);
